package com.ym521.emojipack.util

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.graphics.Point
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import java.util.concurrent.atomic.AtomicInteger

/**
 * @author Ym
 */
object Utils {
    var keyboardHeight = 0
    private val sNextGeneratedId = AtomicInteger(1)

    /**
     * 生成一个适合在｛@link View#setId（int）｝中使用的值。
     * 此值不会与生成时aapt为R.ID生成的ID值冲突。
     *
     * @返回生成的ID值
     */
    @JvmStatic
    fun generateViewId(): Int {
        while (true) {
            val result = sNextGeneratedId.get()
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            var newValue = result + 1
            if (newValue > 0x00FFFFFF) newValue = 1 // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result
            }
        }
    }

    fun getSoftKeyboardHeight(context: Context?): Int {
        return 200
    }

    fun getScreenHeight(context: Context): Int {
        val windowManager =
            context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        return size.y
    }

    fun getScreenWidth(context: Context): Int {
        val windowManager =
            context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        return size.x
    }

    fun isKeyboardShowing(context: Context): Boolean {
        return context.resources.configuration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
    }

    @JvmStatic
    fun hideInput(activity: Activity) {
        val view = activity.window.peekDecorView()
        view?.let {
            hideInput(it)
        }
    }

    @JvmStatic
    fun hideInput(view: View) {
        val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    @JvmStatic
    fun dip2px(view: View, dpValue: Float): Int {
        return dip2px(view.context,dpValue)
    }
    @JvmStatic
    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }
}